package com.egu.web.controller;

import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.egu.model.User;
import com.egu.model.UserRole;
import com.egu.service.UserRoleService;
import com.egu.service.UserService;

@Controller
public class LoginController {

	@Autowired
	private UserService userService;
	
	@Autowired 
	private UserRoleService userRoleService;
	
	@RequestMapping(value="login",method=RequestMethod.GET)
	public String login() {
		return "login";
	}
	
	@RequestMapping(value="login",method=RequestMethod.POST)
	public String login(String userNum,String userPw, HttpSession session,Model model) {
		User user = this.userService.findUserByUserName(userNum);
		if (user == null) {
			model.addAttribute("messages","账号不存在");
			return "login";
		}
		if (!DigestUtils.md5Hex(userPw).equals(user.getUserPw())) {
			model.addAttribute("messages","账号密码不一致");
			return "login";
		}
		//获取当前用户的角色
		UserRole userRole = userRoleService.getUserRoleByCurrentUser(user);
		//保存当前用户信息和用户权限到session中
		Integer rolePower = userRole.getRolePower();
		user.setRoleName(userRole.getRoleName());
		user.setRolePower(userRole.getRolePower());
		session.setAttribute("currentUser", user);
		session.setAttribute("rolePower", rolePower);
		return "redirect:/admin/home";
	}
	
	@RequestMapping("logout")
	public String logout(HttpSession session,Model model) {
		session.invalidate();
		model.addAttribute("messages",null);
		return "redirect:/login";
	}
}
